package cn.mason.echarts.controller;


import cn.mason.echarts.model.User;
import cn.mason.echarts.service.UserService;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.security.token.SSOToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @author yesyoungbaby
 * @date 2018/6/8
 */

@Controller
public class LoginController {
    private Logger logger= LoggerFactory.getLogger(this.getClass());
    @Autowired
    UserService userService;

    /**
     * @param account
     * @param password
     * @return 登录结果
     */
    @Login
    @RequestMapping(value = "/loginByAccount", method = RequestMethod.POST)
    public String loginByAccount(@RequestParam("account") String account,
                                 @RequestParam("password") String password,
                                 HttpServletResponse response,
                                 HttpServletRequest request) {
        //logger.info("账户信息-------------",account);
        //logger.info("密码信息-------------",password);


        if (account == null || password == null || "".equals(account) || "".equals(password)) {
            return "login";
        }
            Map params = new HashMap();
            params.put("account", account);
            params.put("password", password);
            Iterator itr = userService.listByParams(params).iterator();
            if (itr.hasNext()) {
                User user=(User)itr.next();
                SSOToken ssoToken=new SSOToken();
                ssoToken.setId(user.getId());
                SSOHelper.setCookie(request,response,ssoToken,true);
                return "index";
            } else {
                return "login";
            }
        }
        @RequestMapping(value = "/logout",method = RequestMethod.GET)
        public String logout(HttpServletRequest request,HttpServletResponse response) {
            SSOHelper.clearLogin(request,response);
            return "login";
        }


}
